import axios from 'axios'
import { fromJS } from 'immutable'
import * as types from './action-types'

const setHomeData = (data) => ({
  type: types['SET_HOME_DATA'],
  topicList: fromJS(data.topicList),
  articleList: fromJS(data.articleList),
  recommendList: fromJS(data.recommendList),
  writerList: fromJS(data.writerList)
})

const addHomeData = (data, page) => ({
  type: types['ADD_HOME_DATA'],
  data: fromJS(data),
  page: fromJS(page + 1)
})

export const changeBackTopAction = (show) => ({
  type: types['CHANGE_BACK_TOP'],
  show
})

export const getHomeDataAction = () => {
  return (dispatch) => {
    axios.get('/api/home.json')
      .then(res => {
        const result = res.data
        if (result.success) {
          dispatch(setHomeData(result.data))
        }
      })
  }
}

export const addHomeDataAction = (page) => {
  return (dispatch) => {
    axios.get(`/api/homeList.json?page=${page}`)
      .then(res => {
        const result = res.data
        if (result.success) {
          dispatch(addHomeData(result.data, page))
        }
      })
  }
}
